<template>
    <div class="box" @scroll="scrollFun">
        <!-- 使用组件 -->
        <headers title="搜索"></headers>
        <!-- 搜索框 -->
        <div style="display: flex; align-items: center;">
            <van-search v-model="title" placeholder="请输入搜索关键词" style="flex: 1;" />
            <span @click="showPopup">筛选</span>
        </div>
        <!-- 右侧弹出 -->
        <van-popup v-model:show="show" position="right" closeable :style="{ width: '60%', height: '100%' }">
            <van-search v-model="title" placeholder="请输入搜索关键词" style="flex: 1;" />
            <div>
                <van-button type="primary" @click="show = false">
                    确定
                </van-button>
                <van-button type="default" @click="show = false">
                    取消
                </van-button>
            </div>
        </van-popup>
        <!-- 有值渲染 -->
        <template v-if="listData.length > 0">
            <van-pull-refresh v-model="loading" @refresh="onRefresh">
                <van-list :loading="loading1" :finished="finished" finished-text="没有更多了" @load="onLoad">
                    <van-card v-for="(v, i) in listData" :key="i" :price="v.goods_price" :title="i + v.goods_name"
                        thumb="" @click="toDeatil(v.goods_id)">
                        <template #thumb>
                            <!-- 将来图片懒加载 -->
                            <!-- <img style="width: 6rem;height: 6rem;"
                                :src="v.goods_small_logo ? v.goods_small_logo : 'https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg'"
                                alt="" srcset=""> -->
                            <lazy-component>
                                <img style="width: 6rem;height: 6rem;"
                                    v-lazy="v.goods_small_logo ? v.goods_small_logo : 'https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg'" />
                            </lazy-component>
                        </template>
                    </van-card>
                </van-list>
            </van-pull-refresh>
        </template>
        <!-- 暂无数据处理 -->
        <template v-else>
            <van-empty description="暂无数据" />
        </template>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { searchApis } from '@/api/api';
//引入组件 
import headers from '@/components/headers.vue';
//引入鲁大师库
import _ from 'lodash'
// ==============================页面滚动方法==================================
const scrollFun = (e) => {
    localStorage.setItem('searchTop', e.target.scrollTop)
}
// ==============================搜索页面接受上个页面的参数==================================
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()

let title = ref(route.query.name)
// ———————————— 搜索列表数据 ————————————
let pagenum = ref(1);
let listData = ref([]);
let total = ref(0);
const getsearchApi = () => {
    searchApis(title.value, pagenum.value).then((res) => {
        listData.value = [...res.data.message.goods, ...listData.value]; // 数组拼接（加载更多时拼接数据）
        total.value = res.data.message.total; // 数据总条数

        setTimeout(() => {
            document.querySelector('.box').scrollTop =
                localStorage.getItem('searchTop')
        }, 100)
    });
};
getsearchApi(); // 页面初始化时立即调用

// ———————————— watch 监听搜索条件（如 title 变化），重置分页与数据 ————————————
watch(
    title,
    _.debounce((newValue, oldValue) => {
        pagenum.value = 1; // 搜索条件变化，页数重置为第 1 页
        listData.value = []; // 清空原有数据，重新加载
        loading1.value = false; // 触底加载的 loading 重置
        finished.value = false; // 触底加载的 finished 重置
        getsearchApi(); // 调用接口重新获取数据
    }, 1000)
);

// ———————————— 下拉刷新功能（基于 Vant） ————————————
import { showToast } from "vant";
const loading = ref(false);
const onRefresh = () => {
    setTimeout(() => {
        showToast("刷新成功");
        loading.value = false;
        pagenum.value = 1; // 刷新后页数重置为第1页
        listData.value = []; // 清空数据重新加载
        loading1.value = false; // 触底加载状态重置
        finished.value = false; // 触底加载状态重置
        getsearchApi(); // 调用接口重新获取数据
    }, 1000);
};

// ———————————— 无线下拉、触底加载（移动端分页加载更多） ————————————
const loading1 = ref(false);
const finished = ref(false);

const onLoad = () => {
    console.log("触发触底加载");
    // 计算总页数，判断是否还有下一页
    if (Math.ceil(total.value / 20) > pagenum.value) {
        pagenum.value++; // 页数 +1
        getsearchApi(); // 调用接口加载下一页
    } else {
        // 已加载全部数据
        finished.value = true; // 标记“加载完毕”
        loading1.value = false; // 关闭加载中状态
    }
};

// ———————————— 跳转到详情页面 ————————————
const toDeatil = (goods_id) => {
    router.push({ path: "/detail", query: { goods_id: goods_id } });
};
// ———————————— 打开抽屉弹框 ————————————
const show = ref(false);
const showPopup = () => {
    show.value = true;
};

</script>


<style lang="scss" scoped>
.box {
    overflow: auto;
}
</style>